package com.ls.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ls.base.BaseResult;
import com.ls.base.BaseResultUtil;
import com.ls.controller.model.serviceIn.AddServiceInModel;
import com.ls.controller.model.serviceIn.QueryServiceInModel;
import com.ls.entity.*;
import com.ls.mapper.CommChannelMapper;
import com.ls.mapper.CommServiceMapper;
import com.ls.mapper.SmsChannelInMapper;
import com.ls.mapper.SmsServiceInMapper;
import com.ls.service.ISmsServiceInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

import static com.ls.base.BaseResultUtil.SQL_ERROR;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author pengyu
 * @since 2019-12-05
 */
@Service
public class SmsServiceInServiceImpl extends ServiceImpl<SmsServiceInMapper, SmsServiceIn> implements ISmsServiceInService {

    @Autowired
    SmsServiceInMapper mapper;

    @Autowired
    CommServiceMapper serviceMapper;

    @Override
    public BaseResult add(AddServiceInModel model, SysUser currentUser) {
        Long serviceId = model.getServiceId();
        CommService commService = serviceMapper.selectById(serviceId);
        if(commService==null){
            return BaseResultUtil.error("chanId："+serviceId+" 在库里不存在");
        }
        int inNo = model.getInNo();
        if(inNo<0 || inNo >99999){
            return BaseResultUtil.error("inNo 太小或太大："+inNo);
        }
        SmsServiceIn smsServiceIn = new SmsServiceIn();
        smsServiceIn.setServiceId(serviceId);
        smsServiceIn.setInNo(inNo);
        smsServiceIn.setAfterStock(commService.getStock() + inNo);
        smsServiceIn.setCreateTime(LocalDateTime.now());
        smsServiceIn.setCreateUserId(currentUser.getUserId());
        smsServiceIn.setUpdateTime(LocalDateTime.now());
        smsServiceIn.setUpdateUserId(currentUser.getUserId());
        int result = mapper.insert(smsServiceIn);
        if(result>0){
            commService.setStock(commService.getStock() + inNo);
            commService.setTotalNo(commService.getTotalNo() + inNo);
            serviceMapper.updateById(commService);
            return BaseResultUtil.success();
        }else{
            return BaseResultUtil.error(SQL_ERROR);
        }
    }

    @Override
    public BaseResult list(QueryServiceInModel model, SysUser currentUser) {
        QueryWrapper<SmsServiceIn> wrapper = new QueryWrapper<SmsServiceIn>().eq("service_id",model.getServiceId());
        IPage<SmsServiceIn> pageData = mapper.selectPage(new Page<>(model.getPageNum(), model.getPageSize()), wrapper);
        return BaseResultUtil.success(pageData);
    }

}
